package models

import (
	"encoding/json"
	"errors"
	"time"
)

// Post 帖子表
type Post struct {
	PostId 			uint64		`json:"post_id,string" gorm:"post_id"`
	AuthorId 		uint64		`json:"author_id" gorm:"author_id"`
	CommunityId 	uint64		`json:"community_id" gorm:"community_id" binding:"required"`
	Status 			int32		`json:"status" gorm:"status"`
	Title 			string		`json:"title" gorm:"title" binding:"required"`
	Content 		string		`json:"content" gorm:"content" binding:"required"`
	CreateTime 		time.Time	`json:"-" gorm:"create_time"`
	UpdateTime 		time.Time	`json:"-" gorm:"update_time"`
}
func (*Post) TableName() string{
	return "post"
}
// UnmarshalJSON 为Post类型实现自定义的UnmarshalJSON方法
func (p *Post) UnmarshalJSON(data []byte) (err error) {
	required := struct {
		Title       string `json:"title" gorm:"title"`
		Content     string `json:"content" gorm:"content"`
		CommunityID int64  `json:"community_id" gorm:"community_id"`
	}{}
	err = json.Unmarshal(data, &required)
	if err != nil {
		return
	} else if len(required.Title) == 0 {
		err = errors.New("帖子标题不能为空")
	} else if len(required.Content) == 0 {
		err = errors.New("帖子内容不能为空")
	} else if required.CommunityID == 0 {
		err = errors.New("未指定版块")
	} else {
		p.Title = required.Title
		p.Content = required.Content
		p.CommunityId = uint64(required.CommunityID)
	}
	return
}


// PostDetail 帖子返回的详情结构体
// 包括：帖子内容 所属社区信息 作者名称 投票数据
type PostDetail struct {
	*Post  // 嵌入帖子结构体
	*CommunityDetailRes			`json:"community"` // 嵌入社区信息
	AuthorName          string  `json:"author_name"`
	VoteNum             int64   `json:"vote_num"` // 投票数量
}

type Page struct {
	Total int64 `json:"total"`
	Page  int64 `json:"page"`
	Size  int64 `json:"size"`
}
type PostDetailRes struct {
	Page Page             `json:"page"`
	List []*PostDetail 	  `json:"list"`
}
